import 'package:bluetooth_example/peripheral_list.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:bluetooth/bluetooth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    Bluetooth.addEventHandler(dataCallback: (data){
      print(data);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Blue tooth")),
      body: Center(
        child: Column(
          children: [
            MaterialButton(
              onPressed: () async {
                Bluetooth.connect('BarCode Scanner BLE', showLog: true);
              },
              color: Colors.blue,
              child: Text("start"),
            ),
            Container(
              height: 30,
            ),
            MaterialButton(
              onPressed: () {
                Bluetooth.stop();
              },
              color: Colors.blue,
              child: Text("stop"),
            ),
            SizedBox(height: 30),
            MaterialButton(
              onPressed: () async {
               Status status = await Bluetooth.getStatus();
               print("状态 $status");
              },
              color: Colors.blue,
              child: Text("status"),
            ),
            SizedBox(height: 30),
            MaterialButton(
              onPressed: () async {
                Navigator.of(context).push(
                    MaterialPageRoute(builder: (context) {
                      return PeripheralList();//返回的是需要跳转单页面
                    },));
              },
              color: Colors.blue,
              child: Text("搜索"),
            )
          ],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
      ),
    );
  }
}

